package com.itao.bytebuddy;

import com.itao.util.ResourceUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ByteArrayClassLoader;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;

import java.io.File;
import java.lang.reflect.Constructor;

import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * @Author sjt
 * @CreateTime 2023/10/16 14:20
 */
public class LoadClass {

    public static void main(String[] args) {
        try (
                var unloaded = new ByteBuddy()
                        .rebase(SupperClass.class)
                        //.name("com.itao.bytebuddy.SubClass")
                        .method(named("parent"))
                        .intercept(FixedValue.value("2"))
                        .make()
        ) {
            var loaded = unloaded
                    // 加载到jvm
                    .load(LoadClass.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                    // 获得加载的类
                    .getLoaded();
            Constructor<? extends SupperClass> constructor = loaded.getDeclaredConstructor();
            SupperClass supperClass = constructor.newInstance();
            System.out.println(supperClass.parent());
            unloaded.saveIn(new File(ResourceUtil.getClassPath(CreateClass.class)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
